package demo

import java.io.PrintWriter

import custom.codegen.CusSourceCodeGenerator
import slick.jdbc.JdbcBackend
import slick.sql.SqlProfile.ColumnOption

import scala.concurrent.duration._
import scala.concurrent.{ Await, Future }

object OverlordCodeGenerator {
  val url =
    "jdbc:mysql://127.0.0.1:3306/overlord?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=true&serverTimezone=GMT&nullNamePatternMatchesAll=true&useSSL=false"
  //val url = "jdbc:mysql://19.125.100.5:3306/专利?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=true&serverTimezone=GMT&nullNamePatternMatchesAll=true&useSSL=false"
  val jdbcDriver = "com.mysql.cj.jdbc.Driver"
  val slickProfile = slick.jdbc.MySQLProfile
}

/**
 *  This customizes the Slick code generator. We only do simple name mappings.
 *  For a more advanced example see https://github.com/cvogt/slick-presentation/tree/scala-exchange-2013
 */
trait OverlordCodeGenerator {
  import scala.concurrent.ExecutionContext.Implicits.global
  import OverlordCodeGenerator._

  val db: JdbcBackend#DatabaseDef = slickProfile.api.Database.forURL(
    url,
    driver = jdbcDriver,
    user = "root",
    password = "root")
  // filter out desired tables
  val included: List[String]
  lazy val codegen: Future[slick.codegen.SourceCodeGenerator] = db
    .run {
      slickProfile.defaultTables //.map(_.filter(t => included.map(_.toUpperCase) contains t.name.name.toUpperCase))
        .flatMap { s =>
          slickProfile.createModelBuilder(s, true).buildModel
        }
    }
    .map { model =>
      new CusSourceCodeGenerator(model)
    }
}

object OverlordCodeGeneratorRunnerRunner {
  import scala.concurrent.ExecutionContext.Implicits.global

  object custom extends OverlordCodeGenerator {
    override val included = List( //"PE_Label",
    //"PE_User"
    )
  }

  def main(args: Array[String]): Unit = {

    // write the generated results to file
    Await.ready(
      custom.codegen
        .map { s =>
          val genCode = s.packageCode(
            "slick.jdbc.MySQLProfile",
            "models",
            "CrawlTables",
            s.parentType)
          val writer =
            new PrintWriter(args(0) + "/models/CrawlTables.scala", "utf-8")
          writer.write(genCode)
          writer.close()
        }
        .recover {
          case e: Exception =>
            e.printStackTrace
            throw e
        },
      20.seconds)
  }

}
